/**
 * @description: 钉钉开放平台接口请求
 * @version: 0.0.1
 * @author: hxx
 * @Date: 2023-09-26 16:16:07
 */
import { Config } from '@midwayjs/decorator';
import { Provide, HttpClient } from '@midwayjs/core';

@Provide()
export class ApiDingtalk {

  @Config('dingtalkAuthConfig')
  dingtalkAuthConfig: any;

  /**
   * 获取访问凭证
   * @param {*} appKey 
   * @param {*} authCode 
   * @param {*} appSecret 
   * @returns 
   */
  async userAccessToken(appKey: string, authCode: string, appSecret: string) {
    try {
      const _url = `${this.dingtalkAuthConfig.api_uri}/v1.0/oauth2/userAccessToken`;
      const _data = {
        "clientId": appKey,
        "clientSecret": appSecret,
        "code": authCode,
        "grantType": "authorization_code"
      }
      const _headers = {
        "x-acs-dingtalk-access-token": authCode
      };
      return await this.httpRequest("POST", _url, _data, _headers);
    } catch (error) {
      return { success: false, msg: "sdk-ddTopApi-userAccessToken-系统错误", data: error };
    }
  }

  /**
   * 获取用户通讯录个人信息
   * 文档地址：https://open.dingtalk.com/document/orgapp-server/dingtalk-retrieve-user-information
   * @param {*} token 
   */
  async contactUsers(token: string) {
    try {
      const _url = `${this.dingtalkAuthConfig.api_uri}/v1.0/contact/users/me`;
      const _headers = {
        "x-acs-dingtalk-access-token": token
      };
      return await this.httpRequest("GET", _url, {}, _headers);
    } catch (error) {
      return { success: false, msg: "sdk-ddTopApi-contactUsers-系统错误", data: error };
    }
  }

  /**
   * 批量发送人与机器人会话中机器人消息
   * 文档地址：https://open.dingtalk.com/document/orgapp-server/dingtalk-retrieve-user-information
   * @param {*} token 
   * @param {*} robotCode  机器人的编码。
   * @param {*} userIds 用户的userid。 每次最多传20个。
   * @param {*} msgKey 消息模板key。
   * @param {*} msgParam 消息模板参数。
   */
  async oToMessagesBatchSend({ token, robotCode, userIds, msgKey, msgParam }: { token: string, robotCode: string, userIds: string, msgKey: string, msgParam: object }) {
    try {
      const _url = `${this.dingtalkAuthConfig.api_uri}/v1.0/robot/oToMessages/batchSend`;
      const _headers = {
        "x-acs-dingtalk-access-token": token
      };
      const _data = {
        "robotCode": robotCode,
        "userIds": userIds,
        "msgKey": msgKey,
        "msgParam": JSON.stringify(msgParam)
      }
      return await this.httpRequest("POST", _url, _data, _headers);
    } catch (error) {
      return { success: false, msg: "sdk-ddTopApi-oToMessagesBatchSend-系统错误", data: error };
    }
  }

  /**
     * 发起请求
     * @param {string} method 
     * @param {string} url 
     * @param {string} data 
     * @param {string} headers 
     * @returns 
     */
  async httpRequest(method: string, url: string, data: object = {}, headers: object = {}) {
    // eslint-disable-next-line no-useless-catch
    try {
      const httpclient = new HttpClient();
      const result = await httpclient.request(url, {
        method: method,
        data: data,
        dataType: 'json',
        contentType: 'json',   // 发送的 post 为 json
        headers: {
          'Content-Type': 'application/json',
          ...headers
        }
      });
      return {
        success: (result && result.status == 200) ? true : false,
        ...result.data
      }
    } catch (error) {
      throw error;
    }
  }
}